<?php
/*
 * 权限
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Session;
use app\common\model\AuthRule;
use think\facade\Db;

class Auth extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function lists()
    {
        return $this->fetch('index');
    }
    public function rule_json()
    {
        $authRule = collection(Db::table('auth_rule')->where(['status' => 1])->order('sort_order asc')->select())->toArray();
        return json_encode($authRule);
    }
    //修改状态
    public function status()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AuthRule::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了权限规则状态');
            $this->success('修改成功');
        }
    }
    //添加
    public function add()
    {
        if ($this->request->isPost()) {
            $result = AuthRule::create($this->request->param());
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了权限规则');
            $this->success('添加成功');
        }
        return $this->fetch('save', ['list' => list_to_level(Db::table('auth_rule')->where(['status' => 1])->order('sort_order asc')->select())]);
    }
    //修改
    public function edit()
    {
        if ($this->request->isPost()) {
            $result = AuthRule::update($this->request->param());
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了权限规则');
            $this->success('修改成功');
        }
        return $this->fetch('save', [
            'data' => Db::table('auth_rule')->find(input('id')),
            'list' => list_to_level(Db::table('auth_rule')->where(['status' => 1])->order('sort_order asc')->select())
        ]);
    }
    //删除
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('auth_rule')->where('pid', input('id'))->count() && $this->error('请先删除子节点');
            AuthRule::destroy($param['id']);
            insert_admin_log('删除了权限规则');
            $this->success('删除成功');
        }
    }
}
